package com.jd.genie.agent.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
public class OkHttpUtil {

    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    /**
     * 创建带有超时设置的 OkHttpClient
     *
     * @param connectTimeout 连接超时时间
     * @param readTimeout    读取超时时间
     * @param writeTimeout   写入超时时间
     * @return 配置好超时的 OkHttpClient 实例
     */
    private static OkHttpClient createClient(long connectTimeout, long readTimeout, long writeTimeout)
    {
        return new OkHttpClient.Builder()
                .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                .readTimeout(readTimeout, TimeUnit.SECONDS)
                .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 发送 POST 请求，以 JSON 格式传递参数
     *
     * @param url        请求的 URL
     * @param jsonParams JSON 格式的参数
     * @return 请求结果
     * @throws IOException 网络请求异常
     */
    public static String postJson(String url, String jsonParams, Map<String, String> headers, Long timeout) throws IOException
    {
        OkHttpClient client = createClient(timeout, timeout, timeout);
        RequestBody body = RequestBody.create(jsonParams, JSON);
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(body);
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        Request request = requestBuilder.build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                return response.body().string();
            }
        }
        return null;
    }

}